const multer = require('@koa/multer');

const storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, './assets/uploads/');
	},
	filename: function (req, file, cb) {
		let fileFullName;
		// 解决中文文件名乱码问题
		file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf-8');
		if (file.originalname.includes('.')) {
			const fileInfoArr = file.originalname.split('.');
			fileFullName = fileInfoArr[0] + '_' + Date.now() + '.' + fileInfoArr[1];
		} else {
			fileFullName = file.originalname + '_' + Date.now();
		}
		cb(null, fileFullName);
	},
});

const limits = {
	files: 3,
	fileSize: 1024 * 1024 * 10, // 10MB
};

function fileFilter(req, file, cb) {
	switch (file.mimetype.split('/')[0]) {
		case 'image':
			cb(null, true);
			break;
		case 'audio':
			req.status = {
				code: 0,
				data: null,
				msg: '不支持上传该类型文件',
			};
			cb(null, false);
			break;
		case 'video':
			req.status = {
				code: 0,
				data: null,
				msg: '不支持上传该类型文件',
			};
			cb(null, false);
			break;
	}
}

const uploadInstance = multer({
	storage,
	fileFilter,
	limits,
});

module.exports = uploadInstance;
